import React from 'react';
import ReactDOM from 'react-dom';
import { matchPath } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import configureStore from './models/store';
import createRouter from './routes';

const store = configureStore(window.__initState__);
const router = createRouter({});

const render = async (Component) => {
    let _route = null;
    router.routeConfig.some(route => {
        let match = matchPath(window.location.pathname, route);
        if(match && match.path) {
            _route = route;
            return true;
        }
    });

    await _route.component.preload();

    ReactDOM.render((
        <Provider store={store}>
            <BrowserRouter>
                <Component />
            </BrowserRouter>
        </Provider>
    ), document.getElementById('root'));
}

// 热更新
if(module.hot) {
    module.hot.accept('./routes/index.js', () => {
        const createRouter = require('./routes').default;
        render(createRouter({}).dom)
    })
}

render(router.dom);